import { useState } from "react";
async function updateNameInDB(newName) {
  await new Promise((resolve) => setTimeout(resolve, 1500));
  if (newName.toLowerCase().includes("error")) {
    throw new Error("Failed to update name");
  }
  return newName;
}
function FormSubmit() {
  const [input, setInput] = useState("");
  const [name, setName] = useState("Anonymous user");

  function handleChange(event) {
    setInput(event.target.value);
  }

  async function handleSubmit(event) {
    event.preventDefault();
    try {
      const newName = await updateNameInDB(input);
      setName(newName);
      setInput("");
    } catch (error) {
      console.error(error.message);
    }
  }

  return (
    <>
      <p className="username">
      FormSubmit Current user: <span>{name}</span>
      </p>
      <form onSubmit={handleSubmit}>
        <input type="text" value={input} onChange={handleChange} required />
        <button type="submit">Update</button>
      </form>
    </>
  );
}

function FormAction() {
  const [name, setName] = useState("Anonymous user");

  async function handleAction(formData) {
    event.preventDefault();
    try {
      const newName = await updateNameInDB(formData.get("name"));
      setName(newName);
    } catch (error) {
      console.error(error.message);
    }
  }

  return (
    <>
      <p className="username">
        FormAction Current user: <span>{name}</span>
      </p>
      <form action={handleAction}>
        <input name="name" type="text" required />
        <button type="submit">Update</button>
      </form>
    </>
  );
}

export default FormAction;
export { FormSubmit };
